/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package psn.shan.xml.enhancedvalidator.util;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.transform.stream.StreamSource;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.input.sax.XMLReaderJDOMFactory;
import org.jdom2.input.sax.XMLReaderXSDFactory;

/**
 * @author Shan
 * 
 *         XmlUtils Utility for managing XML
 * 
 */
public final class XmlUtils {

	/*
	 * TODO: Cache the loaded XML file to ensure it is not loaded for each relation
	 */
	public static Document parseXML(String aXMLFile, String aXSDFile)
			throws JDOMException, IOException {
		XMLReaderJDOMFactory lSchemaFactory = new XMLReaderXSDFactory(
				XmlUtils.class.getClassLoader().getResource(aXSDFile));

		SAXBuilder lBuilder = new SAXBuilder(lSchemaFactory);

		return lBuilder.build(XmlUtils.class.getClassLoader().getResource(
				aXMLFile));
	}

	/*
	 * TODO: Cache the loaded XML file to ensure it is not loaded for each relation
	 */
	public static Document parseXML(InputStream aXMLFile, InputStream aXSDFile)
			throws JDOMException, IOException {
		XMLReaderJDOMFactory lSchemaFactory = new XMLReaderXSDFactory(new StreamSource(aXSDFile));

		SAXBuilder lBuilder = new SAXBuilder(lSchemaFactory);

		return lBuilder.build(aXMLFile);
	}

	/*
	 * TODO: Cache the loaded XML file to ensure it is not loaded for each relation
	 */
	public static Document parseXML(String aXMLFile) throws JDOMException,
			IOException {
		SAXBuilder lBuilder = new SAXBuilder();

		return lBuilder.build(XmlUtils.class.getClassLoader().getResource(
				aXMLFile));
	}
}
